package com.xtt.httpclient;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * @author ct
 * @description 
 * @createTime 2017年4月3日 下午1:34:47
 */
public class HttpClientUtils {
	
	/**
	 * 获取reponse,注意关闭
	 * @param requestUrl 请求路径
	 * @param proxyHost 代理HttpHost
	 * @param connectTimeout 连接超时时间
	 * @param socketTimeout 传输超时时间
	 * @return CloseableHttpResponse
	 */
	public static CloseableHttpResponse getResponse(String requestUrl, HttpHost proxyHost, Integer connectTimeout, Integer socketTimeout) {
		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet get = new HttpGet(requestUrl);
		get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) "
				+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
		RequestConfig config = RequestConfig.custom()
				.setProxy(proxyHost)
				.setConnectTimeout(connectTimeout)
				.setSocketTimeout(socketTimeout)
				.build();
		get.setConfig(config);
		CloseableHttpResponse response = null;
		try {
			response = client.execute(get);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
		return response;
	}
	
	/**
	 * 获取reponse,连接超时10s，传输超时10s，注意关闭
	 * @param requestUrl 请求路径
	 * @param proxyHost 代理HttpHost 不用代理设为null
	 * @return CloseableHttpResponse
	 */
	public static CloseableHttpResponse getResponse(String requestUrl, HttpHost proxyHost) {
		return getResponse(requestUrl, proxyHost,10000,10000);
	}
	
	/**
	 * 获取响应HttpEntity对象
	 * @param requestUrl 请求路径
	 * @param proxyHost 代理HttpHost
	 * @param connectTimeout 连接超时时间
	 * @param socketTimeout 传输超时时间
	 * @return
	 */
	public static HttpEntity getEntity(String requestUrl, HttpHost proxyHost, Integer connectTimeout, Integer socketTimeout) {
		CloseableHttpResponse response = getResponse(requestUrl, proxyHost, connectTimeout, socketTimeout);
		HttpEntity entity = response.getEntity();
		return entity;
	}
	/**
	 * 获取响应HttpEntity对象 连接超时10s，传输超时10s，
	 * @param requestUrl 请求路径
	 * @param proxyHost 代理HttpHost
	 * @return HttpEntity
	 */
	public static HttpEntity getEntity(String requestUrl, HttpHost proxyHost) {
		return getEntity(requestUrl, proxyHost, 10000, 10000);
	}
	
}
